#ifndef OBJLOADER_H
#define OBJLOADER_H


#include <string>
#include <D3D11.h>
#include <D3DX11.h>
#include <xnamath.h>
#include <d3dx11Effect.h>

using std::string;

struct Vertex
{
	XMFLOAT3 position;
	XMFLOAT3 normal;
	XMFLOAT3 tangent;
	XMFLOAT2 tex;
};

struct Material
{
    

    XMFLOAT4 vAmbient;	
    XMFLOAT4 vDiffuse;		// xyz: diffuse  + w:alpha
    XMFLOAT4 vSpecular;		// xyz: specular + w:shininess 
	XMFLOAT4 vIsTextured;		// x: hasDiffuseTex, y: hasSpecularTex, z: hasNormalTex

	std::wstring   strName;
    std::wstring	strTexture;
	std::wstring	strTextureNormal;
	std::wstring	strTextureSpecular;

    ID3D11ShaderResourceView* pTextureRV10;
	ID3D11ShaderResourceView* pTextureNormalPRV10;
	ID3D11ShaderResourceView* pTextureSpecularPRV10;

    ID3DX11EffectTechnique*  pTechnique;

	Material() : vIsTextured(XMFLOAT4(0.0f, 0.0f, 0.0f, 0.0f)) , pTextureRV10(0), pTextureNormalPRV10(0), pTextureSpecularPRV10(0) { }
};



class OBJLoader
{

	public:
		OBJLoader();
		~OBJLoader();

		void load(	ID3D11Device*	g_device,
					const char*		filename, 
					ID3D11Buffer**				vertex_buffer, 
					ID3D11Buffer**				index_buffer, 
					Material&					_material, 
					UINT&						n_vertices, 
					UINT&						n_indices, 
					ID3D11ShaderResourceView**	srv=0);


		UINT GetNumSubsets() const
		{
			return m_NumAttribTableEntries;
		}

		Material* getMaterial(int i) const { return &(materials[i]); }
		
		int getMaterialCount() const { return material_count; }

	private:

		void computeTriTangent();
		void computeVertexTangent();

		bool firstPass(std::ifstream& file);
		bool secondPass(std::ifstream& file);
		bool materialPass();

		XMFLOAT3* positions;
		XMFLOAT3* normals;
		XMFLOAT2* uvs;
		
		Vertex*		 vertices;
		DWORD*		 indices;
		DWORD*		 attributes;

		Material*	 materials;

		std::string mtl_file;

		ID3D11Device* g_device;


		UINT        m_NumAttribTableEntries;

		UINT position_count;
		UINT normal_count;
		UINT uv_count;

		UINT index_count;
		UINT vertex_count;

		XMFLOAT3* tri_tangents;

		std::wstring strName;

		int material_count;
		UINT face_count;
};


#endif